import _ from 'lodash'

let util = {}
util.title = function (title) {
  title = title ? title + ' - Home' : '千语管理中心'
  window.document.title = title
}

util.getCompressedEncodedData = function (file) {
  return new Promise(function (resolve, reject) {
    // let sizeLimit = 5 * 1024 * 1024
    let img = new Image()
    let maxW = 750

    img.onload = function () {
      let cvs = document.createElement('canvas')
      let ctx = cvs.getContext('2d')

      if (img.width > maxW) {
        img.height *= maxW / img.width
        img.width = maxW
      }

      cvs.width = img.width
      cvs.height = img.height

      ctx.clearRect(0, 0, cvs.width, cvs.height)
      ctx.drawImage(img, 0, 0, img.width, img.height)

      // const dataUrl = cvs.toDataURL(file.type, getCompressRate(sizeLimit, file.size))
      const dataUrl = cvs.toDataURL(file.type)
      resolve(dataUrl.replace(`data:${file.type};base64,`, ''))
    }
    img.src = file.preview
  })
}

const flattenTree = function (tree = [], flattened = [], depth = 0, sortFn = null) {
  if (typeof sortFn === 'function') {
    tree = sortFn(tree)
  }
  _.forEach(tree, function (item) {
    item.depth = depth
    flattened.push(item)
    if (item.children) {
      flattened = flattenTree(item.children, flattened, depth + 1, sortFn)
    }
  })
  return flattened
}

util.flattenTree = flattenTree

export default util
